package com.rfid;

import android.util.Log;

import com.android.serialport.itf.ISerialController;
import com.android.serialport.utils.ByteUtils;
import com.rfid.analysis.Handler;
import com.rfid.analysis.HandlerAddress;
import com.rfid.analysis.HandlerCRC;
import com.rfid.analysis.HandlerChain;
import com.rfid.analysis.HandlerCommand;
import com.rfid.analysis.HandlerData;
import com.rfid.analysis.HandlerHeader;
import com.rfid.analysis.HandlerLength;
import com.rfid.analysis.HandlerStatus;
import com.rfid.analysis.Message;
import com.rfid.protocol.Instruction;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @author Administrator
 * @date 2020/11/28
 */
public class RFIDDataAnalysis {

    private DealDataRunnable dataRunnable;
    private CopyOnWriteArrayList<byte[]> mUidList = new CopyOnWriteArrayList<>();
    private int i = 0;
    private ISerialController mISerialController;
    private Thread mThread;


    public RFIDDataAnalysis(ISerialController controller) {
        mISerialController = controller;
        List<Instruction> mCommandList = new ArrayList<>();

//        mCommandList.add(new InventoryCommand(new ParseDataListener() {
//            @Override
//            public void onData(byte[] data) {
//                if (data != null) {
//                    mUidList.add(Arrays.copyOfRange(data, 1, data.length));
//                } else {
//                    //盘点结束
//                    if (!mUidList.isEmpty()) {
//                        //查询数据块
//                        mISerialController.write(getBlockDataCommand(mUidList.get(0)));
//                    } else {
//                        if (isInventorying) {
//                            try {
//                                Thread.sleep(100);
//                                mISerialController.write(ByteUtils.hexToByteArr("EC07FFFE0100C1B4"));
//                            } catch (InterruptedException e) {
//                                e.printStackTrace();
//                            }
//                        }
//                    }
//                }
//            }
//        }));
//        mCommandList.add(new DataBlockCommand(new ParseDataListener() {
//            @Override
//            public void onData(byte[] data) {
//                i++;
//                if (data != null) {
//                    parseBlockData(data);
//                    if (i < mUidList.size()) {
//                        mISerialController.write(getBlockDataCommand(mUidList.get(i)));
//                    } else {
//                        i = 0;
//                        mUidList.clear();
//                        //数据解析完成，再次盘点
//                        if (isInventorying) {
//                            try {
//                                Thread.sleep(100);
//                                mISerialController.write(ByteUtils.hexToByteArr("EC07FFFE0100C1B4"));
//                            } catch (InterruptedException e) {
//                                e.printStackTrace();
//                            }
//                        }
//                    }
//                }
//            }
//        }));

        Message message = new Message();
        HandlerChain chain = new HandlerChain();
        Handler head = new HandlerHeader();
        chain.addHandler(head)
                .addHandler(new HandlerLength())
                .addHandler(new HandlerAddress())
                .addHandler(new HandlerCommand(mCommandList))
                .addHandler(new HandlerStatus())
                .addHandler(new HandlerData())
                .addHandler(new HandlerCRC())
                .addHandler(head);
        message.setFirstHandler(head);
        message.setCurrentNodeHandler(head);

        dataRunnable = new DealDataRunnable(message);
        //Executors.newSingleThreadExecutor().submit(dataRunnable);
        mThread = new Thread(dataRunnable);
        mThread.start();
    }

    private volatile boolean isInventorying = false;

    public void startInventory() {
        isInventorying = true;
        mISerialController.write(ByteUtils.hexToByteArr("EC07FFFE0100C1B4"));
    }

    public void stopInventory() {
        isInventorying = false;
    }

    public void analysis(byte[] data) {
        if (dataRunnable != null) {
            dataRunnable.putData(data);
        }
    }

    public void stop() {
        if (dataRunnable != null) {
            dataRunnable.stop();
        }
    }

    private byte[] getBlockDataCommand(byte[] uid) {
        String command = "11FFFE2300" + ByteUtils.bytesToHexString(uid) + "0003";
        command = "EC" + command + ByteUtils.CRC16(command);
        return ByteUtils.hexToByteArr(command);
    }

    private void parseBlockData(byte[] data) {
        byte[] cardNo = new byte[7];
        System.arraycopy(data, 13, cardNo, 0, 2);
        System.arraycopy(data, 16, cardNo, 2, 4);
        System.arraycopy(data, 21, cardNo, 6, 1);
        StringBuilder tStringBuf = new StringBuilder();
        char[] charsNo = new char[7];
        for (int i = 0; i < 7; i++) {
            charsNo[i] = (char) cardNo[i];
        }
        tStringBuf.append(charsNo);
        String strNo = tStringBuf.toString();
        Log.e("parseBlockData", strNo);
       // EventBus.getDefault().post(new ReadEvent(strNo));
    }

} 